﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using si.caha.Repository;
using si.caha.Model;

namespace si.caha.Repository
{
    public class ImageRepository : BaseRepository
    {
        public ImageRepository(DataContext dataConext) : base(dataConext){}
        
        public Image Get(int ImageId)
        {
            return GetDataContext().Images.SingleOrDefault(i => i.ImageId == ImageId);
        }

        public void Delete(int ImageId)
        {
            Image imageToDelete = Get(ImageId);
            GetDataContext().Images.Remove(imageToDelete);
            GetDataContext().SaveChanges();
        }

        public void Save(Image entity)
        {
            GetDataContext().Images.Add(entity);
            GetDataContext().SaveChanges();
        }

        public void SetFrontImage(int imageId)
        {
            GetDataContext().Images.SingleOrDefault(i => i.ImageId == imageId).FrontImage = true;
            // only for images of one item
            int itemId = GetDataContext().Images.SingleOrDefault(i => i.ImageId == imageId).ItemId;
            GetDataContext().Images.Where(i => (i.ImageId != imageId && i.ItemId == itemId)).ToList().ForEach(i => i.FrontImage = false);

            GetDataContext().SaveChanges();
        }
    }
}